package com.heba.greenmulu.message;

import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.android.gms.common.internal.AccountType;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.ItemMessageChatDetailAdapter;
import com.heba.bean.message.ItemMessageDetailObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.greenmulu.businesslist.BusinessHomePageActivity;
import com.heba.greenmulu.businesslist.BusinessPersonActivity;
import com.heba.greenmulu.diary.ItemPersonHomePageActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.ToastShow;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 與好友聊天的界面(傳送文章、產品和名片等)
 * Created by jason on 2020/1/14.
 */
public class ItemMessageChatDetailActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_avatar;

    private EditText et_content;
    private ImageView iv_send;

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ItemMessageChatDetailAdapter recycleAdapter;

    private List<ItemMessageDetailObject> list;

    /**
     * 接收的数据
     */
    private String fromUserID;
    private String fromUserName;
    private String fromUserIcon;
    private int fromAccountType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_chat_detail);
        initTopbar();
        findViewById();
        initView();
        getMessageDetailListData();
    }

    @Override
    protected void findViewById() {
        iv_avatar = findViewById(R.id.iv_avatar);
        et_content = findViewById(R.id.et_content);
        iv_send = findViewById(R.id.iv_send);
        refreshLayout = findViewById(R.id.refreshLayout);
        recyclerView = findViewById(R.id.recyclerView);
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            fromUserID = bundle.getString(CommonConfig.SEND_USER_ID, "");
            fromUserName = bundle.getString(CommonConfig.USER_NAME, "");
            fromUserIcon = bundle.getString(CommonConfig.USER_ICON, "");
            fromAccountType = bundle.getInt(CommonConfig.ACCOUNT_TYPE,0);
        }
        txt_title.setText(fromUserName);
        GlideUtil.loadImageWithPlaceHolderID(this, fromUserIcon, iv_avatar, R.drawable.icon_head_portrait);

        list = new ArrayList<>();

        recycleAdapter = new ItemMessageChatDetailAdapter(this, list);

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);

        //设置禁止刷新
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            Page = 1;
            isRefreshFromTop = true;
            getMessageDetailListData();
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Page++;
            isRefreshFromTop = false;
            getMessageDetailListData();
        });

        iv_avatar.setOnClickListener(this);
        txt_title.setOnClickListener(this);
        iv_send.setOnClickListener(this);
    }

    /**
     * 获取聊天消息列表数据
     */
    private void getMessageDetailListData() {
        if (firstRefresh) {
            firstRefresh = false;
            progressDialog.show();
        }
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("p", Page);
        params.put("pp", 9999);
        params.put("FromUserID", fromUserID);
        client.get(Cfg.BaseUrl + "/Transfer/Listing", params,
                new JSONHttpHelper.JSONHttpResponseHandler(this) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);

                        /**
                         * 下拉刷新处理
                         */
                        if (isRefreshFromTop) {
                            isRefreshFromTop = false;
                            refreshLayout.setNoMoreData(false);
                            list.clear();
                        }

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemMessageDetailObject> messageDetailObjects = new Gson().fromJson(array.toString(), new TypeToken<List<ItemMessageDetailObject>>() {
                                }.getType());
                                list.addAll(list.size(), messageDetailObjects);
                            } else {
                                //无数据
                                refreshLayout.finishLoadMoreWithNoMoreData();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新数据
                        recycleAdapter.notifyDataSetChanged();
                        //移动到最后一个item
                        recyclerView.scrollToPosition(list.size() - 1);
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                        closeRefreshView(refreshLayout);
                    }

                });
    }

    /**
     * 发送文本讯息
     */
    private void sendTextMessage() {
        loading.Start();
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                loading.End();
                et_content.setText("");
                isRefreshFromTop = true;
                getMessageDetailListData();
            }

            @Override
            public void Fail(String error) {
                loading.End();
                if (error.equals("ERR_BLACKLIST") ){
                    ToastShow.displayToast(getBaseContext(), getResources().getString(R.string.had_bloack));
                }
            }
        }).sendTextMessage(this, CommonUtils.getEncodeText(et_content.getText().toString()), fromUserID);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_avatar:
            case R.id.txt_title:
                Bundle bundle = new Bundle();
                bundle.putString(CommonConfig.SEND_USER_ID, fromUserID);
                if (fromAccountType == 0){
                    openActivity(ItemPersonHomePageActivity.class,bundle);
                }else{
                    openActivity(BusinessPersonActivity.class,bundle);
                }
                break;
            case R.id.iv_send:
                if (et_content.getText().toString().trim().isEmpty())
                    return;
                sendTextMessage();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MessageEvent event = new MessageEvent();
        event.setEvent(CommonConfig.EVENT_UPDATE_MESSAGE);
        EventBus.getDefault().post(event);
    }
}
